//
//  CityWeather.swift
//  ZhiYunWeather
//
//  Created by Wade on 2024/7/9.
//

import Alamofire
import Foundation
import Kingfisher
import LGSideMenuController
import SDWebImage
import SVProgressHUD
import UIKit
import ZFPlayer

class KEAlphabetNewDetail: KYBaseVC {
    var content: String?
    // 字母卡片
    var aBtn: UIButton?
    // 单词卡片
    var wordBtn: UIButton?
    // 单词卡片
    var preBtn: UIButton?
    var nextBtn: UIButton?
    // 单词卡片
    var wordEnBtn: UIButton?
    var sentenceBtn: UIButton?
    var mLanBtn: UIButton?
    
    // 练习按钮
    var mTrainingBtn: UIButton?
    lazy var gameVC: KEAlphabetGame = .init()
    
    var selectIndex: Int = 0
    var springView: SpringView?
    var springView2: SpringView?
    var currentWords: KEWordsDetail?
    var currentIndex: Int = -1
   // 当前字母的单词列表
    var menuList: [KEWordsDetail]?
    // 测试配套的单词列表
    var wordList: [KEWordsDetail]?
    var gameList: [KEGameModel]? = Array()
    override func viewDidLoad() {
        self.view.backgroundColor = .qmui_color(withHexString: "#A2D6E9")
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        setupSubViews()
        self.audioPlayer = ZFAudioPlayer()
        self.collectionView?.register(KEAlphabetCollectionCell.self, forCellWithReuseIdentifier: "KEAlphabetCollectionCell")
        
        self.springView?.alpha = 0
        self.loadData()
    }
    
    /*
     public enum AnimationPreset: String {
         case SlideLeft = "slideLeft"
         case SlideRight = "slideRight"
         case SlideDown = "slideDown"
         case SlideUp = "slideUp"
         case SqueezeLeft = "squeezeLeft"
         case SqueezeRight = "squeezeRight"
         case SqueezeDown = "squeezeDown"
         case SqueezeUp = "squeezeUp"
         case FadeIn = "fadeIn"
         case FadeOut = "fadeOut"
         case FadeOutIn = "fadeOutIn"
         case FadeInLeft = "fadeInLeft"
         case FadeInRight = "fadeInRight"
         case FadeInDown = "fadeInDown"
         case FadeInUp = "fadeInUp"
         case ZoomIn = "zoomIn"
         case ZoomOut = "zoomOut"
         case Fall = "fall"
         case Shake = "shake"
         case Pop = "pop"
         case FlipX = "flipX"
         case FlipY = "flipY"
         case Morph = "morph"
         case Squeeze = "squeeze"
         case Flash = "flash"
         case Wobble = "wobble"
         case Swing = "swing"
     }
     
     public enum AnimationCurve: String {
         case EaseIn = "easeIn"
         case EaseOut = "easeOut"
         case EaseInOut = "easeInOut"
         case Linear = "linear"
         case Spring = "spring"
         case EaseInSine = "easeInSine"
         case EaseOutSine = "easeOutSine"
         case EaseInOutSine = "easeInOutSine"
         case EaseInQuad = "easeInQuad"
         case EaseOutQuad = "easeOutQuad"
         case EaseInOutQuad = "easeInOutQuad"
         case EaseInCubic = "easeInCubic"
         case EaseOutCubic = "easeOutCubic"
         case EaseInOutCubic = "easeInOutCubic"
         case EaseInQuart = "easeInQuart"
         case EaseOutQuart = "easeOutQuart"
         case EaseInOutQuart = "easeInOutQuart"
         case EaseInQuint = "easeInQuint"
         case EaseOutQuint = "easeOutQuint"
         case EaseInOutQuint = "easeInOutQuint"
         case EaseInExpo = "easeInExpo"
         case EaseOutExpo = "easeOutExpo"
         case EaseInOutExpo = "easeInOutExpo"
         case EaseInCirc = "easeInCirc"
         case EaseOutCirc = "easeOutCirc"
         case EaseInOutCirc = "easeInOutCirc"
         case EaseInBack = "easeInBack"
         case EaseOutBack = "easeOutBack"
         case EaseInOutBack = "easeInOutBack"
     }
     */
    
    override func viewWillAppear(_ animated: Bool) {
        self.springView?.alpha = 1
        self.springView?.duration = 1.25
        self.springView?.rotate = 2.0
        self.springView?.animation = "fadeInDown"
        self.springView?.animateNext(completion: {})
        
        self.springView2?.alpha = 1
        self.springView2?.duration = 1.25
        self.springView2?.rotate = 2.0
        self.springView2?.animation = "fadeInRight"
        self.springView2?.animateNext(completion: {})
    }
    
    // 获取
    func loadData() {
        let param = ["letter": self.content!, "level": 0] as [String : Any]
        AF.request("https://fc-mp-d6f030db-0e27-458b-906b-ae7d21ab9004.next.bspapp.com/getWords/getWordsByQuery", method: .post, parameters: param, encoding: JSONEncoding.default).responseDecodable(of: KEWordResult.self) { res in
                    switch res.result {
                    case .success(let result):
                        let words = result.result
                        if words!.count > 0 {
                            self.menuList = words
                        }
                    case .failure:
                        print("error:"+res.error.debugDescription)
                    }
                }
        
        
//        AF.request("https://fc-mp-d6f030db-0e27-458b-906b-ae7d21ab9004.next.bspapp.com/getWords/getWordsByQuery", method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { res in
//            switch res.result{
//            case .success(let result):
//                let json = result
//                print("json:")
//            case .failure(_):
//                print("error:"+res.error.debugDescription)
//            }
//        }
    }
    
    func setupWordWithIndex(_ index: Int) {
        if index == -1 { return }
        self.currentWords = self.menuList?[index]
        self.aBtn!.setTitle(self.content! + self.content!.lowercased(), for: .normal)
        if (self.currentWords?.word_iamges!.count)! > 0 {
//            wordBtn?.kf.setImage(with: URL(string: self.currentWords?.word_iamges!.first ?? ""), for: .normal)
//            wordBtn?.imageView?.sd_setImage(with: URL(string: self.currentWords?.word_iamges!.first ?? ""))
            self.wordBtn?.sd_setImage(with: URL(string: self.currentWords?.word_iamges!.first ?? ""), for: .normal)
            print("Image:" + (self.currentWords?.word_iamges!.first ?? ""))
        }
        
        if self.currentIndex == -1 {
            self.preBtn?.isHidden = true
        }
        if self.currentIndex == self.menuList!.count - 1 {
            self.nextBtn?.isHidden = true
        }
        let wordEn = self.currentWords?.word_en ?? ""
        let wordZh = self.currentWords?.word_zh ?? ""
        var words = wordEn
        if self.mLanBtn?.isSelected == false {
            words = words + "\n" + wordZh
        }
       
        self.wordEnBtn!.setTitle(words, for: .normal)
        let sentence_en = self.currentWords?.word_sentences!.first?.word_sentences_en ?? ""
        let sentence_zh = self.currentWords?.word_sentences!.first?.word_sentences_zh ?? ""
        var sentence = sentence_en
        if self.mLanBtn?.isSelected == false {
            sentence = sentence + "\n" + sentence_zh
        }
        self.sentenceBtn!.setTitle(sentence, for: .normal)
    }
    
    // 获取
    func pushToGameView() {
        SVProgressHUD.show(withStatus: "正在加载...")
        var letter = ""
        if self.content == "A"||self.content == "B"||self.content == "C" {
            letter = "D"
        } else {
            letter = self.content!
        }
        let param = ["letter": letter, "exceptLetters": [self.content!], "level": 0] as [String: Any]
        AF.request("https://fc-mp-d6f030db-0e27-458b-906b-ae7d21ab9004.next.bspapp.com/getWords/getWordsByQueryToLetter", method: .post, parameters: param, encoding: JSONEncoding.default).responseDecodable(of: KEWordResult.self) { res in
            switch res.result {
            case .success(let result):
                let words = result.result
                if words!.count > 0 {
                    self.wordList = words
                    self.getGameList()
                }
            case .failure:
                print("error")
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                }
            }
        }
    }
    
    func getGameList() {
        self.gameList?.removeAll()
        var gameList = [KEGameModel]()
        for item in self.menuList! {
            // 单词猜图片
            var game1 = KEGameModel()
            game1.gameType = .wordToImage
            game1.anwserWord = item
            game1.questionWords = self.getQuestionListWithAnwser(anwser: item)
            gameList.append(game1)
            
            // 图片猜单词
            var game2 = KEGameModel()
            game2.gameType = .imageToWords
            game2.anwserWord = item
            game2.questionWords = self.getQuestionListWithAnwser(anwser: item)
            gameList.append(game2)
            
            // 图片猜单词
            var game3 = KEGameModel()
            game3.gameType = .audioToWord
            game3.anwserWord = item
            game3.questionWords = self.getQuestionListWithAnwser(anwser: item)
            gameList.append(game3)
            
            // 图片猜单词
//            var game4 = KEGameModel()
//            game4.gameType = .wordToAudio
//            game4.anwserWord = item
//            game4.questionWords = getQuestionListWithAnwser(anwser: item)
//            gameList.append(game4)
            
            // 图片猜单词
//            var game5 = KEGameModel()
//            game5.gameType = .imageToAudio
//            game5.anwserWord = item
//            game5.questionWords = getQuestionListWithAnwser(anwser: item)
//            gameList.append(game5)
            
            // 图片猜单词
            var game6 = KEGameModel()
            game6.gameType = .audioToimage
            game6.anwserWord = item
            game6.questionWords = self.getQuestionListWithAnwser(anwser: item)
            gameList.append(game6)
        }
        self.gameList = gameList
        
        DispatchQueue.main.async {
            SVProgressHUD.dismiss()
        }
        self.gameVC.modalPresentationStyle = .fullScreen
        self.gameVC.gameList = self.gameList
        self.present(self.gameVC, animated: true)
    }
    
    func getQuestionListWithAnwser(anwser: KEWordsDetail) -> [KEWordsDetail] {
        var wordSets = Set<KEWordsDetail>()
        wordSets.insert(anwser)
        while wordSets.count != 4 {
            wordSets.insert((self.wordList?.randomElement())!)
        }
        return Array(wordSets)
    }
}
